<?php
	class Favor extends CActiveRecord{
	/**
	 * Returns the static model of the specified AR class.
	 * @return Post the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return '{{favor}}';
	}

	public function rules(){
		return array();
	}
	public function relations(){
		return array(
			//'favor_user'=>array(self::MANY_MANY, 'Favor', 'user_favor(user_id, favor_id)'),
		);
	}
	public function attributeLabels(){
		return array(
			'favor_id'=>'favor',
			'favor_name'=>'兴趣',
			'user_ids'=>'人数',
			'favor_time'=>'时间',
		);
	}

	public function search(){
		$criteria = new CDbCriteria;
		$criteria->compare('favor_id',$this->favor_id);
		$criteria->compare('favor_name',$this->favor_name,true);
		$criteria->compare('user_ids',$this->user_ids);
		$criteria->compare('favor_time',$this->favor_time);
		return new CActiveDataProvider(get_class($this), array(
			'criteria'=>$criteria,
		));
	}
	public function saveFavor($uid,$favor_name = ' '){
		//$favor_name_array = explode(' ',trim($favor_name));
		$favor_name_array = preg_split('/[\s,]+/',trim($favor_name));
		for($i = 0,$favor_count = count($favor_name_array);$i<$favor_count;$i++){
			$result = self::model()->findAll(array(
				'condition'=>'favor_name=:n',
				'params'=>array(':n'=>$favor_name_array[$i]),
			));
			
			if($result){
				$uid_arr = (array)json_decode($result[0]->attributes['user_ids']);
				if(!in_array($uid,$uid_arr['uids'])){
					$uid_arr['uids'] = array_merge($uid_arr['uids'],array('0'=>$uid));
					$uid_arr['count']+=1;
					$result[0]->user_ids = json_encode($uid_arr);
					$result[0]->user_count =$uid_arr['count'];
					$result[0]->favor_time = $result[0]->attributes['favor_time'];
					$result[0]->save();
				}else{
					continue;
				}
			}else{
				$model = new Favor;
				$model->favor_name = $favor_name_array[$i];
				$model->favor_time = time();
				$model->user_ids = json_encode(array('uids'=>array('0'=>$uid),'count'=>1));
				$model->user_count = 1;
				$model->save();
			}
		}
	}
	}
?>